package com.java1412.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java1412.utils.ConstantUtil;
import com.java1412.utils.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 前台接口的拦截器
 *
 * @author java1412
 * @since 2023-08-10 11:02:36
 */
@Component
public class ApiLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前台接口的拦截器");
        // 获取会话对象
        HttpSession session = request.getSession();
        // 获取当前登录用户
        Object loginUser = session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        // 判断loginUser是否为空
        if (null != loginUser) {
            return true;
        } else {
            // 返回json数据给前端
            response.setContentType("application/json;charset=UTF-8");
            // om对象可以将Object对象转成json
            ObjectMapper om = new ObjectMapper();
            ResponseUtil r = ResponseUtil.fail("用户尚未登录，不能访问该接口");
            String json = om.writeValueAsString(r);
            response.getWriter().write(json);
            // 不能放行
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
